// pages/function/resale/publish/publish.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTop: getApp().globalData.navTop,
    globalImg: getApp().globalData.imageUrl,
    // 导航栏加载
    navLoading: false,
    // 新旧程度
    new: ["全新", "九成新", "七成新", "五成新", "三成新"],
    newIndex: 0,
    // 分类
    // category: ["潮鞋", "包包", "生活闲置", "潮衣", "其它"],
    category: [],
    categoryIndex: 0,
    // 表单数据 
    form: {
      quality: '全新',
      goodsType: 1,
      goodsName: '',
      goodsDescription: '',
      oldPrice: "",
      price: '',
      buyMethod: '',
      contact: '',
      goodsPhotos: '',
      deleted: 0,
      username: wx.getStorageSync('userInfo').nickName,
    },
    // 子组件传的img
    imgUrl: '',
    // 页面参数
    goodsId: '',
    // 传给子组件的图片
    sonPhoto: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options)
    this.getCategory()
    if (options.id) {
      this.setData({
        goodsId: options.id - 0
      })
      this.getGoodsById()
    }

    // console.log(this.data.new.indexOf('七成新'))
  },
  // 根据id获取商品
  async getGoodsById() {
    wx.showLoading({
      title: '加载中...',
    })
    const res = await getApp().requestWithToken.get(`/sechandGoods/getGoodsById/${this.data.goodsId}`)
    // console.log(res)
    if (res.code === 200) {
      let resForm = {}
      resForm.updateTime = res.data.updateTime
      resForm.id = res.data.id
      for (const key in this.data.form) {
        for (const key2 in res.data) {
          if (key === key2) {
            resForm[key] = res.data[key2]
          }
        }
      }

      wx.hideLoading()
      this.setData({
        form: resForm,
        newIndex: this.data.new.indexOf(res.data.quality),
        categoryIndex: res.data.goodsType - 1,
        sonPhoto: this.data.globalImg + res.data.goodsPhotos
      })
    }
  },
  // 新旧程度
  changeNew(e) {
    this.setData({
      newIndex: e.detail.value,
      ['form.quality']: this.data.new[e.detail.value - 0]
    })
  },
  // 分类
  changeCategory(e) {
    this.setData({
      categoryIndex: e.detail.value,
      ['form.goodsType']: this.data.category[e.detail.value - 0].id
    })
  },
  // 子组件传的imgUrl
  imgUrl(e) {
    this.setData({
      imgUrl: e.detail.value
    })
    const that = this
    wx.uploadFile({
      filePath: this.data.imgUrl,
      name: 'file',
      url: getApp().globalData.url + '/sechandGoods/uploadImage',
      header: {
        'authorization': wx.getStorageSync("token"),
        'content-type': 'application/json'
      },
      success(res) {
        // console.log(res.data)
        const newImg = res.data.split(":")[3].split("}")[0].split("\"")[1]
        // console.log(newImg)
        that.setData({
          ['form.goodsPhotos']: newImg,
        })
      }
    })
  },
  // 现价
  newPrice(e) {
    const that = this
    // console.log(e)
    const exp = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    // exp.test(e.detail.value)
    // console.log(exp.test(e.detail.value))
    if (!exp.test(e.detail.value)) {

      wx.showModal({
        content: '请输入正确的金额',
        showCancel: true,
        success() {
          that.setData({
            ['form.price']: null
          })
        }
      })
    } else {
      this.setData({
        ['form.price']: e.detail.value - 0
      })
    }

  },

  // 原价
  oldPrice(e) {
    const that = this
    const exp = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    exp.test(e.detail.value)
    console.log(exp.test(e.detail.value))
    if (!exp.test(e.detail.value)) {
      wx.showModal({
        content: '请输入正确的金额',
        showCancel: true,
        success() {
          that.setData({
            ['form.oldPrice']: null
          })
        }
      })
    } else {
      this.setData({
        ['form.oldPrice']: e.detail.value - 0
      })
    }
  },

  // 提交数据
  submitGoods(e) {
    this.setData({
      ['form.goodsName']: e.detail.value.goodName,
      ['form.goodsDescription']: e.detail.value.goodDesc,
      ['form.oldPrice']: e.detail.value.oldPrice,
      ['form.price']: e.detail.value.newPrice,
      ['form.buyMethod']: e.detail.value.buyMethod,
      ['form.contact']: e.detail.value.wechat,
    })
    // console.log(Object.keys(this.data.form).length)
    const that = this
    // 建议属性值上传是否为空
    const isEmpty = function () {
      for (const key in that.data.form) {
        // console.log(that.data.form[key])
        if (that.data.form[key] === '') {
          return false
        }
      }
    }
    // console.log(isEmpty())
    if (isEmpty() == undefined) {
      this.saveGoods()
    } else {
      wx.showToast({
        title: '有内容为空，请输入完整',
        icon: "none"
      })
    }
  },

  // 保存商品数据的接口
  async saveGoods() {
    wx.showLoading({
      title: '发布中',
    })
    this.setData({
      navLoading: true
    })
    let res = ''
    if (this.data.goodsId) {
      res = await getApp().requestWithToken.post('/sechandGoods/updateGoods', {
        data: this.data.form
      })
      // console.log('更新成功')
    } else {
      res = await getApp().requestWithToken.post('/sechandGoods/saveGoods', {
        data: this.data.form
      })
      // console.log('保存成功')
    }
    if (res.code === 200) {
      wx.hideLoading()
      this.setData({
        navLoading: false
      })
      wx.showToast({
        title: '发布成功',
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/function/resale/resale',
        })
      }, 700)
    } else {
      this.setData({
        navLoading: false
      })
      wx.showToast({
        title: '发布失败',
        icon: 'error'
      })
    }
  },

  // 获得分类的数据
  async getCategory() {
    const res = await getApp().requestWithToken.get('/type/getList')
    if (res.code === 200) {
      this.setData({
        category: res.data
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})